package com.yuju.controller.login;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.redis.jfinal.plugin.Redis;
import com.yuju.common.Result;
import com.yuju.constant.CacheKey;
import com.yuju.constant.Config;
import com.yuju.constant.Constant;
import com.yuju.controller.base.BaseController;
import com.yuju.enums.ReturnCodeEnum;
import com.yuju.enums.ReturnStatusEnum;
import com.yuju.enums.UserTypeEnum;
import com.yuju.login.model.EmployeeModel;
import com.yuju.login.model.MemberModel;
import com.yuju.login.model.OwnerCustomModel;
import com.yuju.login.service.IEmployeeService;
import com.yuju.login.service.IMemberService;
import com.yuju.login.service.IOwnerCustomService;
import com.yuju.login.enums.OpReturnCodeEnum;
import com.yuju.login.model.MenuModel;
import com.yuju.login.model.OpHotelModel;
import com.yuju.login.model.OpModel;
import com.yuju.login.service.ILoginService;
import com.yuju.login.service.IMenuService;
import com.yuju.login.service.IOpHotelService;
import com.yuju.model.TreeModel;
import com.yuju.util.ConfigUtil;
import com.yuju.util.TokenUtils;
import com.yuju.util.Utils;
import com.yuju.vo.login.OpVO;

/**
 * 
 * 类名：LoginController  <br />
 *
 * 功能：登录
 *
 * @author : xuehj <br />
 * @Date : 2018年1月16日 下午5:15:08  <br />
 * @version : 1.1 <br />
 */
@Controller
@RequestMapping("login")
public class LoginController extends BaseController<OpVO, OpModel> {
	@Autowired
	private ILoginService loginService;
	
	@Autowired
	private IEmployeeService employeeService;
	
	@Autowired
	private IOwnerCustomService ownerCustomService;
	
	@Autowired
	private IMemberService memberService;
	
	@Autowired
	private IMenuService menuService;
	
	@Autowired
	private IOpHotelService opHotelService;

	/**
	 * 
	 * 功能：登录<br/>
	 *
	 * @author zhousc
	 * @Date 2017年12月4日 下午5:14:45 <br/>
	 */
	
	@RequestMapping("pwdLogin")
	@ResponseBody
	public Result pwdLogin(@RequestBody JSONObject obj) {
		OpVO opVO = obj.toJavaObject(OpVO.class);
		
		Result result = new Result();
		
		//查询是否有此账号
		OpModel opModel = loginService.login(convert(opVO));
		
		if (Utils.isNull(opModel)) {
			result.setStatus(ReturnStatusEnum.FAILURE.getCode());
			result.setMsg(ReturnStatusEnum.FAILURE.getDesc());
			result.setReturnCode(ReturnCodeEnum.LOGIN_USER_NOT_FOUND.getCode());
			result.setReturnMsg(ReturnCodeEnum.LOGIN_USER_NOT_FOUND.getDesc());
			return result;
		}
		
		// 账户已被禁止使用
		if (opModel.getStatus() == Constant.USER_STATUS_DISABLED) {
			result.setStatus(ReturnStatusEnum.FAILURE.getCode());
			result.setMsg(ReturnStatusEnum.FAILURE.getDesc());
			result.setReturnCode(OpReturnCodeEnum.OP_PROHIBITED_FAILURE.getCode());
			result.setReturnMsg(OpReturnCodeEnum.OP_PROHIBITED_FAILURE.getDesc());
			return result;
		}
		
		String pwd = opModel.getUserId() + opVO.getPassword() + opModel.getSalt() ;
		//进行SHA加密
		try {
			MessageDigest instance = MessageDigest.getInstance("SHA-256");
			byte[] digest = instance.digest(pwd.getBytes("UTF-8"));
			//产生加密密码
			String encodeHexString = Hex.encodeHexString(digest);
			//判断密码是否正确
			if(encodeHexString.equals(opModel.getPassword())){
				/**
				 * 判断用户类型，加载对应的用户数据
				 */
				// PMS用户
				if (UserTypeEnum.PMS_USER.getValue() == opModel.getUserType()) {
					EmployeeModel empInfo = employeeService.findById(opModel.getUserId());
					if (Utils.isNotNull(empInfo)) {
						opModel.setEmpId(empInfo.getId());
						opModel.setCode(empInfo.getCode());
						opModel.setEmployeeName(empInfo.getName());
						opModel.setUserCode(empInfo.getCode());
						opModel.setUserName(empInfo.getName());
					}
				} // 业主用户
				else if (UserTypeEnum.OWNER_USER.getValue() == opModel.getUserType()) {
					OwnerCustomModel ownerInfo = ownerCustomService.findById(opModel.getUserId());
					if (Utils.isNotNull(ownerInfo)) {
						opModel.setUserName(ownerInfo.getName());
					}
				} // 微信会员用户
				else if (UserTypeEnum.WECHAT_USER.getValue() == opModel.getUserType()) {
					MemberModel memberInfo = memberService.findById(opModel.getUserId());
					if (Utils.isNotNull(memberInfo)) {
						opModel.setUserCode(memberInfo.getCardCode());
						opModel.setUserName(memberInfo.getName());
					}
				} // 平台用户
				else if (UserTypeEnum.PLA_USER.getValue() == opModel.getUserType()) {
					
				}
				
				//用于包装返回数据
				Map<String, Object> returnMap = new HashMap<>();
				returnMap.put("opInfo", opModel);

				//根据账号ID查询分店权限范围
				List<OpHotelModel> opHotelList = opHotelService.hotelListByOpId(opModel.getId());
				if (Utils.isNotNull(opHotelList) && !opHotelList.isEmpty()) {
					//包装到返回分店范围数据
					returnMap.put("hotelList", opHotelList);
				}
				
				//账号菜单权限范围数据
				List<MenuModel> menuList = menuService.menuListByOpId(opModel.getId());
				if (Utils.isNotNull(menuList) && !menuList.isEmpty()) { 
					//重新包装菜单
					List<TreeModel> menuTree = menuService.menuTree(menuList);
					//包装返回菜单数据
					returnMap.put("menuList", menuTree);
				}
				//包装返回登录账号信息
				opModel.setPassword(null);
				
				// 子系统访问接口
				Map<String, String> urls = new HashMap<String, String>();
				urls.put(Constant.URL_PMS_SERVER, ConfigUtil.get(Constant.URL_PMS_SERVER));
				urls.put(Constant.URL_IMS_BACK_SERVER, ConfigUtil.get(Constant.URL_IMS_BACK_SERVER));
				urls.put(Constant.URL_GUEST_SERVER, ConfigUtil.get(Constant.URL_GUEST_SERVER));
				urls.put(Constant.URL_FILE_SERVER, ConfigUtil.get(Constant.URL_FILE_SERVER));
				urls.put(Constant.URL_IMG_SERVER, ConfigUtil.get(Constant.URL_IMG_SERVER));
				returnMap.put("urls", urls);

				result.setData(returnMap);
				

				// 将用户信息放入缓存
				cacheUser(opModel);
				
				result.setStatus(ReturnStatusEnum.SUCCESS.getCode());
				result.setMsg(ReturnStatusEnum.SUCCESS.getDesc());
				result.setReturnCode(ReturnCodeEnum.LOGIN_SUCCESS.getCode());
				result.setReturnMsg(ReturnCodeEnum.LOGIN_SUCCESS.getDesc());
			} else {
				result.setStatus(ReturnStatusEnum.FAILURE.getCode());
				result.setMsg(ReturnStatusEnum.FAILURE.getDesc());
				result.setReturnCode(ReturnCodeEnum.LOGIN_PWD_ERROR.getCode());
				result.setReturnMsg(ReturnCodeEnum.LOGIN_PWD_ERROR.getDesc());
			}
		} catch(Exception e) {
			e.printStackTrace();
			result.setStatus(ReturnStatusEnum.FAILURE.getCode());
			result.setMsg(ReturnStatusEnum.FAILURE.getDesc());
			result.setReturnCode(ReturnCodeEnum.LOGIN_FAILURE.getCode());
			result.setReturnMsg(ReturnCodeEnum.LOGIN_FAILURE.getDesc());
		}
		return result;
	}

	/**
	 * 
	 * 功能：将用户信息放入缓存<br/>
	 *
	 * @author xuehj
	 * @Date 2017年12月13日 下午1:55:37 <br/>
	 */
	private void cacheUser(OpModel user) {
		String token = TokenUtils.create(user.getName());
		user.setToken(token);
		Redis.use().setex(token + CacheKey.KEY_CACHE_USER, Config.CACHE_DEFAULT_TIME_SECONDS, JSON.toJSONString(user));
	}
}
